﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Net;

namespace thread
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

       

        private async void SearchButton_Click_1Async(object sender, EventArgs e)
        {
            string keyword = KeywordTextBox.Text;
            if (string.IsNullOrWhiteSpace(keyword))
            {
                MessageBox.Show("请输入关键字！");
                return;
            }

            BaiduResultTextBox.Clear();
            BingResultTextBox.Clear();

            var tasks = new Task<string>[2];
            tasks[0] = Search("https://search.sohu.com/?keyword=", keyword);
            tasks[1] = Search("https://www.bing.com/search?q=", keyword);

            await Task.WhenAll(tasks);

            BaiduResultTextBox.Text = GetSnippet(tasks[0].Result);
            BingResultTextBox.Text = GetSnippet(tasks[1].Result);
        }
        private string GetSnippet(string str)
        {
            string v = "";
            string pattern = @"^[\u300a\u300b]|[\u4e00-\u9fa5]|[\uFF00-\uFFEF]|[，。！]";
            if (Regex.IsMatch(str, pattern))
            {
                //提示的代码
                Match m = Regex.Match(str, pattern);

                while (m.Success)
                {
                    if (m.Value == ",")
                    {
                        v += m.Value;
                        continue;
                    }
                    v += m.Value;
                    m = m.NextMatch();
                }
            }
            return v;
        }
        private async Task<string> Search(string baseUrl, string keyword)
        {
            using (var client = new HttpClient())
            {
                var url = baseUrl + keyword;
                WebClient webClient = new WebClient();
                byte[] recvdata = webClient.DownloadData(url);
                string response = Encoding.UTF8.GetString(recvdata);
                return response;
            }
        }

        
    }
}
